package com.ladlee.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ladlee.enums.LoginType;
import com.ladlee.properties.SecurityProperties;
import com.ladlee.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: dingchang
 * @Date: 2018/12/22 14:47
 * @Description: 登陆成功的处理器
 */
@Slf4j
@Component(value = "loginSuccessHandler")
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    SecurityProperties securityProperties;

    /**
     * 登陆成功处理器
     * @param request
     * @param response
     * @param authentication
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        log.info("【MerryyouAuthenticationSuccessHandler】 onAuthenticationSuccess authentication={}", authentication);
        if(LoginType.JSON.equals(securityProperties.getLoginType())){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(ResultUtils.success(authentication.getName())));
        }else{
            super.onAuthenticationSuccess(request,response,authentication);
        }
    }
}
